package com.example.demo.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.example.demo.common.ResponseData;
import com.example.demo.domain.Student.StudentInfo;
import com.example.demo.domain.Student.StudentSave;
import com.example.demo.mapper.stuMapper.StuEducationMapper;
import com.example.demo.mapper.stuMapper.StuMapper;
import com.example.demo.mapper.stuMapper.StuSaveMapper;
import com.example.demo.service.IStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class StudentServiceImpl implements IStudentService {
    @Autowired
    StuMapper stuMapper;
    @Autowired
    StuEducationMapper stuEducationMapper;
    @Autowired
    StuSaveMapper stuSaveMapper;

    @Override
    @Transactional//对数据进行更改，并且影响的行数>1
    public ResponseData<String> update(StudentInfo studentInfo) {
        //学号查询学生是否存在
        StudentInfo student=stuMapper.getStudent(studentInfo.getStuNum());
        //如果不存在就新增，否则就修改信息
        boolean add= ObjectUtil.isEmpty(student);
        if (add){
            //新增学生信息
            stuMapper.addStudent(student);
            //新增学生学历
            stuEducationMapper.addList(studentInfo.getStudentEducationList());
        }else {
            //修改学生信息
            stuMapper.updateStudent(student);
            //删除历史学生的学历信息
            stuEducationMapper.delete(studentInfo.getStuNum());
        }
        return ResponseData.ok();
    }

    @Override
    public ResponseData<String> save(StudentSave studentSave) {
        if (StrUtil.isBlank(studentSave.getStuNum())){
            return ResponseData.fail("学号不能为空");
        }
        if(StrUtil.isBlank(studentSave.getClassId())){
            return ResponseData.fail("班级id不能为空");
        }
        boolean selectStu=ObjectUtil.isEmpty(stuSaveMapper.saveStu(studentSave));
        boolean selectClass=ObjectUtil.isEmpty(stuSaveMapper.saveClass(studentSave));
        if (selectStu){
            return ResponseData.fail("没有学生为这个学号");
        }
        if (selectClass){
            return ResponseData.fail("没有此班级id");
        }
        return ResponseData.ok("可以进行维护");
    }
}
